package com.tianyang.yukuaifuzs.business.auth.presenter;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSONObject;
import com.tianyang.yukuaifuzs.business.auth.bean.AreaCityOutput;
import com.tianyang.yukuaifuzs.business.auth.bean.AuthCompanyOutput;
import com.tianyang.yukuaifuzs.business.auth.bean.BankRegOutput;
import com.tianyang.yukuaifuzs.business.auth.bean.IdCardOutput;
import com.tianyang.yukuaifuzs.business.auth.bean.LicenseRegOutput;
import com.tianyang.yukuaifuzs.business.auth.contract.AuthCompanyContract;
import com.tianyang.yukuaifuzs.business.auth.contract.AuthConfig;
import com.tianyang.yukuaifuzs.business.auth.model.AuthModel;
import com.tianyang.yukuaifuzs.business.main.bean.UserCenterOutput;
import com.tianyang.yukuaifuzs.business.main.provider.MainOpenProvider;
import com.tianyang.yukuaifuzs.common.cache.CacheManage;
import com.tianyang.yukuaifuzs.common.cache.CacheModel;
import com.tianyang.yukuaifuzs.common.interfaces.CommonConfig;
import com.tianyang.yukuaifuzs.common.interfaces.IUploadFileCallback;
import com.tianyang.yukuaifuzs.common.utils.AreaCheckListener;
import com.tianyang.yukuaifuzs.common.utils.CommonViewUtils;
import com.tianyang.yukuaifuzs.common.utils.SingleCheckListener;
import com.tianyang.yukuaifuzs.jump.eventbus.RefreshUserEvent;
import com.tianyang.yukuaifuzs.jump.oss.AliyunOSSUtils;
import com.tianyang.yukuaifuzs.module.dialog.HintDialog;
import com.tianyang.yukuaifuzs.module.dialog.IconSourceDialog;
import com.tianyang.yukuaifuzs.module.dialog.interfaces.ISourceChooseListener;
import com.tianyang.yukuaifuzs.module.dialog.interfaces.OnBtnClickL;
import com.tianyang.yukuaifuzs.utils.AlbumUtil;
import com.tianyang.yukuaifuzs.utils.FileUtil;
import com.tianyang.yukuaifuzs.utils.IntentTool;
import com.tianyang.yukuaifuzs.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：企业商户进件
 * Created by xyj on 2024/3/8
 */
public class AuthCompanyPresenter implements AuthCompanyContract.Presenter {

    private AuthCompanyContract.View mView;

    private CompositeSubscription mSubscription;

    private IconSourceDialog vIconSourceDialog;

    private AreaCheckListener mAreaCheckListener;

    private SingleCheckListener mSingleCheckListener;

    private boolean isUploadFile = false, isAgent;

    private Uri imageUri;//拍照文件的路径

    private File outputImage;//拍照文件的地址

    private String provName, cityName, areaName, provCode, cityCode, areaCode, currentPhotoType,
            userName, userId, posStatus, posChannel;

    public AuthCompanyPresenter(AuthCompanyContract.View mView, String userName, String posStatus, boolean isAgent) {
        this.mView = mView;
        this.userName = userName;
        this.posStatus = posStatus;
        this.isAgent = isAgent;
        mSubscription = new CompositeSubscription();
        getIdCertTemp();
        UserCenterOutput output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (output != null) {
            userId = output.getUserId() + "";
        }
    }

    /**
     * Description:查询进件临时数据
     */
    private void getIdCertTemp() {
        mView.showLoadingDialog(false, "查询商户信息...");
        Subscription subscription = AuthModel.getInstance().getIdCertTemp(userName)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(JSONObject output) {
                        if (output != null) {
                            mView.showCompanyInfoView(output.toJavaObject(AuthCompanyOutput.class));
                        }
                    }
                });
        mSubscription.add(subscription);
    }


    @Override
    public void saveIdCertTemp(Map<String, String> map, boolean isAuth, boolean isNextStep, String posChannel) {
        this.posChannel = posChannel;
        if (isAuth) {
            mView.showLoadingDialog(true, "上传进件数据...");
        } else {
            mView.showLoadingDialog(true, "保存商户信息...");
        }
        Subscription subscription = AuthModel.getInstance().saveIdCertTemp(map, userName, AuthConfig.MCH_TYPE_COMPANY)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(Object obj) {
                        if (isAuth) {
                            if (isAgent && TextUtils.equals(AuthConfig.POS_CHANNEL_FY, posChannel)) {
                                mView.dismissLoadingDialog();
                                map.put("tel", userName);
                                map.put("type", "0");
                                map.put("merchantType", AuthConfig.MCH_TYPE_COMPANY);
                                map.put("businessType", "1");
                                map.put("mchType", AuthConfig.MCH_TYPE_COMPANY);
                                if (!map.containsKey("accBankType"))
                                    map.put("accBankType", "2");
                                if (TextUtils.equals("0", posStatus))
                                    map.put("registerType", "1");
                                else
                                    map.put("registerType", posStatus);
                                MainOpenProvider.getInstance().openRateConfigActivity(mView.getContext(),
                                        userName, 0, true, posChannel, map);
                            } else {
                                sendIdCert(map);
                            }
                        } else {
                            if (isNextStep) {
                                mView.dismissLoadingDialog();
                                mView.showNextStepView();
                            } else {
                                mView.dismissLoadingDialog();
                                new HintDialog(mView.getContext())
                                        .title("保存成功")
                                        .content("您的资料已上传保存成功！")
                                        .show();
                            }
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    private void sendIdCert(Map<String, String> map) {
        Subscription subscription = AuthModel.getInstance().sendIdCert(map, userName, AuthConfig.MCH_TYPE_COMPANY, posStatus)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(Object obj) {
                        new HintDialog(mView.getContext())
                                .title("上传成功")
                                .content("提交成功，请等待审核!")
                                .listener(new OnBtnClickL() {
                                    @Override
                                    public void onBtnClick() {
                                        EventBus.getDefault().post(new RefreshUserEvent());
                                        IntentTool.finishActivity(mView.getContext());
                                    }
                                }).show();
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void showSelectImgSourceView(String currentPhotoType) {
        if (isUploadFile) return;
        this.currentPhotoType = currentPhotoType;
        vIconSourceDialog = null;
        vIconSourceDialog = new IconSourceDialog(mView.getContext());
        vIconSourceDialog.setListener(new ISourceChooseListener() {
            @Override
            public void pickerClick() {
                AlbumUtil.openAlbum(mView.getContext(), CommonConfig.REQUESTCODE_IMAGE_PICKER);
            }

            @Override
            public void takePhotoClick() {
                String cameraName = "picture/a" + System.currentTimeMillis() + ".jpg";
                //创建file对象，用于储存拍照后的图片，getExternalCacheDir() : 将照片存放在手机的关联缓存目录下
                outputImage = new File(mView.getContext().getFilesDir(), cameraName);
                if (outputImage.getParentFile() != null && !outputImage.getParentFile().exists()) {
                    outputImage.getParentFile().mkdirs();
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(mView.getContext(),
                            mView.getContext().getPackageName() + ".provider.fileProvider", outputImage);
                } else {
                    imageUri = Uri.fromFile(outputImage);
                }
                CommonViewUtils.onPhotographClick(mView.getContext(), currentPhotoType, imageUri, outputImage.getPath());
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CommonConfig.REQUESTCODE_IMAGE_PICKER:
                    if (data == null) return;
                    Uri selectedImage = data.getData();
                    if (selectedImage != null && !TextUtils.isEmpty(selectedImage.getAuthority())) {
                        String filePath = AlbumUtil.getPath(mView.getContext(), selectedImage);
                        if (!TextUtils.isEmpty(filePath)) {
                            onCompress(filePath, currentPhotoType);
                        }
                    }
                    break;
                case CommonConfig.REQUESTCODE_CERTIFICATE_PICKER:
                    if (CommonViewUtils.isFileExists(mView.getContext(), imageUri)) {
                        if (outputImage.exists()) {
                            onCompress(outputImage.getPath(), currentPhotoType);
                        }
                    }
                    break;
            }
        }
    }

    /**
     * 压缩图片
     */
    private void onCompress(String filePath, final String reName) {
        try {
            isUploadFile = true;
            mView.showLoadingDialog(true, "照片压缩处理中...");
            //同步方法请尽量避免在主线程调用以免阻塞主线程
            Observable.just(filePath)
                    .observeOn(Schedulers.io())
                    .map(new Func1<String, List<File>>() {
                        @Override
                        public List<File> call(String filePath) {
                            return FileUtil.luban(mView.getContext(), filePath, reName);
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<File>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            ToastUtil.show("压缩图片出错");
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onNext(List<File> files) {
                            mView.dismissLoadingDialog();
                            if (files != null && files.size() > 0) {
                                uploadOssFile(files.get(0));
                            } else {
                                ToastUtil.show("照片地址不存在");
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show("照片地址异常");
            mView.dismissLoadingDialog();
        }
    }

    /**
     * 上传文件到OSS
     */
    private void uploadOssFile(File file) {
        if (file == null || !file.exists()) {
            ToastUtil.show("照片地址不存在");
            isUploadFile = false;
            return;
        }
        mView.showLoadingDialog(false, "图片上传中...");
        AliyunOSSUtils ossUtils = AliyunOSSUtils.getInstance();
        String url = ossUtils.uploadFile(ossUtils.getFileName(currentPhotoType, userId), file.getPath(), new IUploadFileCallback() {
            @Override
            public void callback(long currentSize, long totalSize) {
                if (currentSize == totalSize) {
                    mView.dismissLoadingDialog();
                }
            }
        });
        isUploadFile = false;
        if (!TextUtils.isEmpty(url)) {
            if (TextUtils.equals(CommonConfig.TYPE_LICENSEPIC, currentPhotoType)) {
                licenseReg(url);
            } else if (TextUtils.equals(CommonConfig.TYPE_IDFROPIC, currentPhotoType)
                    || TextUtils.equals(CommonConfig.TYPE_IDCONPIC, currentPhotoType)) {
                idCardReg(url);
            } else if (TextUtils.equals(CommonConfig.TYPE_CRDFROPIC, currentPhotoType)) {
                bankReg(url);
            } else {
                mView.showPhotoView(url, currentPhotoType);
            }
        } else {
            ToastUtil.show("上传图片失败，请重新上传！");
        }
    }

    /**
     * 身份ORC识别
     */
    private void licenseReg(String url) {
        mView.showLoadingDialog(false, "正在识别证件信息...");
        Subscription subscription = AuthModel.getInstance().licenseReg(url)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LicenseRegOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(LicenseRegOutput output) {
                        mView.showLicenseRegView(output);
                        mView.showPhotoView(url, currentPhotoType);
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 身份ORC识别
     */
    private void idCardReg(String url) {
        mView.showLoadingDialog(false, "正在识别证件信息...");
        Subscription subscription = AuthModel.getInstance().idCardReg(url)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<IdCardOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(IdCardOutput output) {
                        mView.showIdCardView(output);
                        mView.showPhotoView(url, currentPhotoType);
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 银行卡ORC
     */
    private void bankReg(String url) {
        mView.showLoadingDialog(false, "正在识别证件信息...");
        Subscription subscription = AuthModel.getInstance().bankReg(url)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BankRegOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(BankRegOutput output) {
                        mView.showBankCardView(output, currentPhotoType);
                        mView.showPhotoView(url, currentPhotoType);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void queryProvince(View view, String provCityArea, boolean isShop) {
        if (!TextUtils.isEmpty(provCityArea) && provCityArea.contains(" ")) {
            String[] provCityAreas = provCityArea.split(" ");
            provName = provCityAreas[0];
            cityName = provCityAreas[1];
            if (provCityAreas.length > 2)
                areaName = provCityAreas[2];
        }
        mView.showLoadingDialog(false);
        mSubscription.add(AuthModel.getInstance().getProvinceList()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<AreaCityOutput>>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(List<AreaCityOutput> outputs) {
                        if (outputs != null && outputs.size() > 0) {
                            if (mAreaCheckListener == null) {
                                mAreaCheckListener = new AreaCheckListener(mView.getContext());
                            }
                            mAreaCheckListener.handleCheck(view, "请选择省", outputs, provName,
                                    new AreaCheckListener.IWheelDataChangeCallback() {
                                        @Override
                                        public void wheelDataChangeCallback(AreaCityOutput output) {
                                            if (output != null) {
                                                provName = output.getRegionName();
                                                provCode = output.getRegionCode();
                                                queryCity(view, output.getRegionCode(), isShop);
                                            }
                                        }
                                    });
                        }
                    }
                }));
    }

    /**
     * 查询市
     */
    private void queryCity(final View view, String upCode, boolean isShop) {
        mSubscription.add(AuthModel.getInstance().getCityList(upCode)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<AreaCityOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(List<AreaCityOutput> outputs) {
                        if (outputs != null && outputs.size() > 0) {
                            if (mAreaCheckListener == null) {
                                mAreaCheckListener = new AreaCheckListener(mView.getContext());
                            }
                            mAreaCheckListener.handleCheck(view, "请选择市", outputs, cityName,
                                    new AreaCheckListener.IWheelDataChangeCallback() {
                                        @Override
                                        public void wheelDataChangeCallback(AreaCityOutput output) {
                                            if (output != null) {
                                                cityName = output.getRegionName();
                                                cityCode = output.getRegionCode();
                                                queryArea(view, output.getRegionCode(), isShop);
                                            }
                                        }
                                    });
                        }
                    }
                }));
    }

    /**
     * 查询区
     */
    private void queryArea(final View view, String upCode, boolean isShop) {
        mSubscription.add(AuthModel.getInstance().getAreaList(provCode, upCode)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<AreaCityOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(List<AreaCityOutput> outputs) {
                        if (outputs != null && outputs.size() > 0) {
                            if (mAreaCheckListener == null) {
                                mAreaCheckListener = new AreaCheckListener(mView.getContext());
                            }
                            mAreaCheckListener.handleCheck(view, "请选择区", outputs, areaName,
                                    new AreaCheckListener.IWheelDataChangeCallback() {
                                        @Override
                                        public void wheelDataChangeCallback(AreaCityOutput output) {
                                            if (output != null) {
                                                areaName = output.getRegionName();
                                                areaCode = output.getRegionCode();
                                                mView.showProvCityAreaView(provName + " " + cityName + " " + areaName,
                                                        provCode + " " + cityCode + " " + areaCode, isShop);
                                            }
                                        }
                                    });
                        } else {
                            mView.showProvCityAreaView(provName + " " + cityName,
                                    provCode + " " + cityCode, isShop);
                        }
                    }
                }));
    }

    @Override
    public void getBusinessScopeList(View view, String businessScope) {
        mView.showLoadingDialog(false);
        mSubscription.add(AuthModel.getInstance().getBusinessScopeList()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showErrorText(e);
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(List<String> outputs) {
                        mView.dismissLoadingDialog();
                        if (outputs != null && outputs.size() > 0) {
                            if (mSingleCheckListener == null) {
                                mSingleCheckListener = new SingleCheckListener((Activity) mView.getContext());
                            }
                            mSingleCheckListener.handleCheck(view, businessScope, outputs,
                                    new SingleCheckListener.IWheelDataChangeCallback() {
                                        @Override
                                        public void wheelDataChangeCallback(int position) {
                                            mView.showBusinessScopeView(outputs.get(position));
                                        }
                                    }
                            );
                        }
                    }
                }));
    }

    @Override
    public void onDestroyPresenter() {
        if (vIconSourceDialog != null) {
            vIconSourceDialog.dismiss();
            vIconSourceDialog = null;
        }
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
